
import musicMgr from "./musicMgr"
import Toast from "./Toast"
import utils from "./utils"

export default class GameMgr {

    public static readonly instance: GameMgr = new GameMgr()

    http: any = null

    music: any = null

    cardPrefabs: cc.Prefab[] = []
    // 当前关卡
    currentLevel: number = 1
    // 页面渲染的所有card
    renderCardArr: any[] = []

    _layout: cc.Node = null

    _collection: cc.Node = null

    cardWidth: number = null

    cardHeight: number = null

    utils: utils = new utils()

    hasClickedArr: number[] = []

    totalCardNum: number = null

    audioClip = {}

    musicMgr: musicMgr = null

    Toast: Toast = null

    // 游戏进行时产生的卡片
    _gamePrefabs: cc.Prefab[] = []

    nextLevel() {
        this.currentLevel += 1
        this.resetGame()
        this.loadGameByLevel()
    }

    reStartGame(){
        this.currentLevel = 1
        this.resetGame()
        this.initFirstLevel()
    }

    loadGameByLevel(){
        if(this.currentLevel===1){
            this.initFirstLevel()
        }else{
            this.initSecondLevel()
        }
    }

    resetGame(){
        this._gamePrefabs = []
        this.totalCardNum = null
        this.hasClickedArr = []
        this.renderCardArr = []
        this._layout.removeAllChildren()
        this._collection.removeAllChildren()
    }

    /**
     * 第一关card分布
     */
    initFirstLevel() {
        let cardPrefabs = this.cardPrefabs
        let gap = 3
        // 随机生成  0 ～ cardPrefabs-3 之间的数字
        let startIndex = Math.floor(Math.random() * (cardPrefabs.length - gap + 1))
        let prefabs = cardPrefabs.slice(startIndex, startIndex + gap)
        // 循环生成6组
        let loopNum = 6
        this._gamePrefabs = this.cloneArr(loopNum, prefabs)
        this.totalCardNum = loopNum * prefabs.length
        this.showFirstLevel()
    }

    /**
 * 第二关card分布
 */
    initSecondLevel() {
        let cardPrefabs = this.cardPrefabs
        // 循环生成6组
        let loopNum = 9
        this._gamePrefabs = this.cloneArr(loopNum, cardPrefabs)
        this.totalCardNum = loopNum * cardPrefabs.length
        this.showSecondLevel()
    }

    showFirstLevel() {
        // 打乱顺序
        let firstPrefabs = this.randomArr(this._gamePrefabs)
        // index为position的指针 满6且排除第0项 那么跳转到下一个position的值
        let index = 0
        let position = [{ x: -200, y: 200 }, { x: 0, y: 200 }, { x: 200, y: 200 }, { x: -200, y: -100 }, { x: 0, y: -100 }, { x: 200, y: -100 }]
        for (let i = 0; i < firstPrefabs.length; i++) {
            let node = cc.instantiate(firstPrefabs[i])
            node.index = i
            if (index > 5) index = 0
            let pos = position[index]
            let vec = new cc.Vec2(pos.x, pos.y + (i / 5 * (-10)))
            node.setPosition(vec)
            this._layout.addChild(node)
            this.addClickEvent(node, i)
            index++
        }
        this.utils.verifyCanRemoveMask()
        this.utils.verifyCanClick()
    }
    showSecondLevel(){
        // 底部的两组卡片 每组6张 定义两个点位 分别为 {x:-280,y:-370} {x:280,y:-370} handleFixedPrefabsBottom处理函数
        let fixedNumBottom = 12
        // 左右的两组卡片 每组6张 定义两个点位 分别为 {x:-280,y:-280} {x:280,y:-280} handleFixedPrefabsBottom处理函数
        let fixedLeftAndRight = 12
        // 打乱顺序
        let firstPrefabsRandom = this.randomArr(this._gamePrefabs)

        let fixedPrefabsBottom = firstPrefabsRandom.slice(0,fixedNumBottom)
        this.handleFixedPrefabsBottom(fixedPrefabsBottom)

        let fixedPrefabsLeftAndRight = firstPrefabsRandom.slice(fixedNumBottom,fixedNumBottom+fixedLeftAndRight)
        this.handleFixedPrefabsLeftAndRight(fixedPrefabsLeftAndRight,fixedNumBottom)

        let firstPrefabs = firstPrefabsRandom.slice(fixedNumBottom + fixedLeftAndRight)
        let index = fixedPrefabsBottom.length + fixedPrefabsLeftAndRight.length
        for (let i = 0; i < firstPrefabs.length; i++) {
            let node = cc.instantiate(firstPrefabs[i])
            node.index = index
            let x = this.randomoneToone(-150,150)
            let y = this.randomoneToone(-250,330)
            let vec = new cc.Vec2(x,y)
            node.setPosition(vec)
            this._layout.addChild(node)
            this.addClickEvent(node, index)
            index++
            console.log(node,"3");

        }
        this.utils.verifyCanRemoveMask()
        this.utils.verifyCanClick()
    }
    
    handleFixedPrefabsBottom(fixedPrefabsBottom){
        let mid = fixedPrefabsBottom.length / 2
        let towPosition = [{x:-280,y:-370},{x:280,y:-370}]
        let currentPos = null
        let offsetX = 0
        let index = 0
        for (let i = 0; i < fixedPrefabsBottom.length; i++) {
            const node = cc.instantiate(fixedPrefabsBottom[i]);
            node.index = index
            if(i<=mid-1){
                //左边的卡片渲染 每一张x要加10
                offsetX = i%mid * (30)
                currentPos = towPosition[0]
            }else{
                //右边边的卡片渲染 每一张x要减10
                offsetX = i%mid * (-30)
                currentPos = towPosition[1]
            }
            let vec = new cc.Vec2(currentPos.x + offsetX,currentPos.y)
            node.setPosition(vec)
            this._layout.addChild(node)
            this.addClickEvent(node, index)
            console.log(node,"1");
            
            index++
        }
    }

    handleFixedPrefabsLeftAndRight(fixedLeftAndRight,length){
        let mid = fixedLeftAndRight.length / 2
        let towPosition = [{x:-290,y:280},{x:290,y:280}]
        let currentPos = null
        let offsetY = 0
        let index = length
        for (let i = 0; i < fixedLeftAndRight.length; i++) {
            const node = cc.instantiate(fixedLeftAndRight[i]);
            node.index = index
            if(i<=mid-1){
                currentPos = towPosition[0]
            }else{
                currentPos = towPosition[1]
            }
            offsetY = i%mid * (-40)
            let vec = new cc.Vec2(currentPos.x,currentPos.y+offsetY)
            node.setPosition(vec)
            this._layout.addChild(node)
            this.addClickEvent(node, index)
            console.log(node,"2");

            index++
        }
    }

    randomoneToone(min,max){
        return Math.floor(Math.random()*((max+1)-min)+min)
    }

    addClickEvent(node: any, index: number) {
        let eventHandler = new cc.Component.EventHandler();
        eventHandler.target = this._layout;
        eventHandler.component = "layoutBtnEvent";
        eventHandler.handler = "onItemClick";
        eventHandler.customEventData = index.toString();
        let button = node.getComponent(cc.Button);
        button.clickEvents.push(eventHandler);
    }

    /**
 * 
 * @param times 复制数组的次数
 * @param arr 数组
 */
    cloneArr(times, arr) {
        let result = []
        for (let index = 0; index < times; index++) {
            result = result.concat(arr)
        }
        return result
    }


    /**
* 打乱数组顺序
*/
    randomArr(tempArr, size?) {
        var indexs = -1,
            lengths = tempArr.length,
            lastIndex = lengths - 1;

        size = size === undefined ? lengths : size;
        while (++indexs < size) {
            var rand = indexs + Math.floor(Math.random() * (lastIndex - indexs + 1));
            let value = tempArr[rand];
            tempArr[rand] = tempArr[indexs];
            tempArr[indexs] = value;
        }
        tempArr.length = size;
        return tempArr;
    }


}
